﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using TmU220PrintHelperV2d0.Entity;
using ZhangLogSysV1d0;

namespace TmU220PrintHelperV2d0.Service
{
    /// <summary>
    /// 使用api接口，读取远程数据库的打印任务数据，并将打印任务添加到打印任务队列
    /// 使用构造函数进行依赖注入
    /// </summary>
    public class ThreadFillPrintTaskQueueV3d0
    {
        /// <summary>
        /// 主任务队列
        /// </summary>
        private ConcurrentQueue<PrintTaskV2d0> MainTaskQueue = null;
        /// <summary>
        /// 已读取记录的id列表，避免重复读取记录
        /// </summary>
        public List<int> LoadedRecordIdList = new List<int>();
        /// <summary>
        /// 最后一个装载的记录的序号，每读取一条记录，序号增加1
        /// </summary>
        public int LastLoadedRecordIndex = 0;
        /// <summary>
        /// 有效时长，单位分钟
        /// </summary>
        public int ValidDuration = 30;
        public bool Running = false;
        /// <summary>
        /// epc扫描线程
        /// </summary>
        private Thread Thread_main = null;
        /// <summary>
        /// 线程序号
        /// </summary>
        public int Thread_index = 0;
        /// <summary>
        /// 数据检测间隔
        /// </summary>
        public int CheckInterval { get; set; }
        public DateTime StartTime { get; set; }
        /// <summary>
        /// 任务缓冲区大小
        /// </summary>
        private int TaskBufferSize = 1000;
        #region 事件
        /// <summary>
        /// 下载打印任务完成
        /// </summary>
        public event EventHandler<PrintTaskV2d0> DownloadPrintTaskOverEvent = null;
        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="taskQueue">主任务队列</param>
        /// <param name="validDuration">任务有效时长，单位分钟。距离当前时间30分钟以内的任务为有效任务</param>
        public ThreadFillPrintTaskQueueV3d0(ConcurrentQueue<PrintTaskV2d0> taskQueue,int validDuration,int intervalOfCheckTask=2)
        {
            LastLoadedRecordIndex = 0;
            Thread_main = null;
            Thread_index = 0;
            MainTaskQueue = taskQueue;
            ValidDuration = validDuration;
            CheckInterval = intervalOfCheckTask;
            StartTime = DateTime.Now;
            TaskBufferSize = 1000;
        }
        /// <summary>
        /// 启动线程
        /// </summary>
        public void StartThread()
        {
            if (MainTaskQueue != null)
            {
                this.Thread_main = new Thread(new System.Threading.ThreadStart(this.ThreadStart));
                this.Running = true;
                //作为后台线程
                this.Thread_main.IsBackground = true;
                //启动线程
                this.Thread_main.Start();
            }
            else
            {
                SimpleLoger.Instance.Error("主任务队列未初始化");
            }
        }
        /// <summary>
        /// 停止线程
        /// </summary>
        public void StopThread()
        {
            this.Running = false;
            if(Thread_main!=null) Thread_main.Abort();
        }
        /// <summary>
        /// 线程启动
        /// </summary>
        private void ThreadStart()
        {
            while (Running)
            {
                try
                {
                    var initPrintMainList = DatabaseHelperV3d0.GetPrintMain();
                    //增加日志
                    string runingHours = ((TimeSpan)(DateTime.Now - StartTime)).TotalHours.ToString("F3");                    
                    //选择任务添加时间为当前时间30分钟之内的记录
                    List<rms_order_print_main> printMainList= initPrintMainList.FindAll(x => ((TimeSpan)(DateTime.Now - x.addtime)).TotalMinutes <= ValidDuration);
                    foreach (var printMain in printMainList)
                    {
                        int id = printMain.id;
                        //确保一个打印任务只添加到队列一次
                        if (!LoadedRecordIdList.Contains(id))
                        {
                            //如果已装载Id列表未包含该id，则将该id加入列表中
                            LastLoadedRecordIndex++;
                            LoadedRecordIdList.Add(id);
                            
                            //避免占用太多空间
                            if (LastLoadedRecordIndex> TaskBufferSize)
                            {
                                //LoadedRecordIdList.RemoveAt(0);
                                int countClear = 0;
                                if (TaskBufferSize >= 1000) countClear = 100;
                                else if (TaskBufferSize >= 500 && TaskBufferSize < 1000) countClear = 50;
                                else if (TaskBufferSize >= 200 && TaskBufferSize < 500) countClear = 20;
                                else countClear = 1;
                                LoadedRecordIdList.RemoveRange(0, countClear);
                                LastLoadedRecordIndex = LastLoadedRecordIndex - countClear;
                            }
                            if (MainTaskQueue != null)
                            {
                                //基于模板和打印数据对象，生成打印任务
                                //根据打印任务选择不同的模板 正常，取消，追单
                                string templeteName = "normal-ticket";
                                if (printMain.is_void.HasValue&&printMain.is_void.Value) templeteName = "void-ticket";
                                else if(printMain.is_remind.HasValue&&printMain.is_remind.Value) templeteName = "remind-ticket";
                                else if(printMain.is_call.HasValue && printMain.is_call.Value) templeteName = "call-ticket";
                                else if(printMain.is_move.HasValue && printMain.is_move.Value) templeteName = "move-ticket";
                                //核心方法，将打印数据与打印模板结合生成最终的打印任务
                                PrintTaskV2d0 task = new PrintTaskV2d0(printMain, templeteName);
                                // 发布任务下载完成事件
                                if (DownloadPrintTaskOverEvent != null) DownloadPrintTaskOverEvent(this, task);
                                MainTaskQueue.Enqueue(task);
                            }
                        }                        
                    }
                    Thread.Sleep(1*1000);//等待2秒进行下一次连接
                }
                catch (Exception ex)
                {
                    //SimpleLoger.Instance.Error(ex);
                }
            }
        }
    }
    
}
